/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Gmail;

import Other.MyTableModel;
import UI.Login;
import UI.ManHinhChinh;
import com.sun.org.apache.xml.internal.dtm.DTM;
import java.awt.Checkbox;
import java.awt.Component;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

/**
 *
 * @author Envy
 */
public class NhanEmail {

    private String receivingHost;
    private ImageIcon icon = new ImageIcon("//Other//icon//1371389699_attach.png", "");
    public static MimeMessage messagesTam[] = null;
    //labelBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Other/icon/1371387531_8.png")))    
    private JLabel lbAttach = new JLabel(this.icon);
    public static Message messages[];
    private JTable table;
    public static String filename1, plain1;
    public int times = 1;
    private String[] columnNames = {"#",
        "Người gửi",
        "Tiêu đề",
        "Ngày gửi",
        "Nội dung"
    //"Tập tin"
    };
    private Folder inbox;
    private DefaultTableModel dtm;

    public void readGmail() throws NoSuchProviderException, MessagingException, IOException {
        /*
         * this will print subject of all messages in the inbox of
         * sender@gmail.com
         */
        if (times == 1) {
            receivingHost = "imap.gmail.com";
            //lbAttach.setIcon(icon);
            //Properties props = System.getProperties();
            Login.props.setProperty("mail.store.protocol", "imaps");
            // I used imaps protocol here
            //Session session = Session.getDefaultInstance(props, null);
            //ImageIcon im  =new ImageIcon("..//Other//icon//1371389699_attach.png");
            Store store = Login.session1.getStore("imaps");
            store.connect("imap.gmail.com", Login.user, Login.pass);

            inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_WRITE);

            dtm = new DefaultTableModel(new Object[][]{}, columnNames) {

                Class[] types = {Boolean.class, String.class, String.class, String.class, String.class, ImageIcon.class};

                @Override
                public Class getColumnClass(int columnIndex) {
                    return this.types[columnIndex];
                }
            };

            times++;
        }

        messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.RECENT), false));
        for (int i = 0; i < messages.length; i++) {
            Multipart mp = (Multipart) messages[i].getContent();
            //String file = mp.getBodyPart(1).getFileName();
//                Boolean chkFile;
//
//                for (int j = 0; j < mp.getCount(); j++) {
//                    MimeBodyPart bp[] = null;
//                    bp[j] = (MimeBodyPart) mp.getBodyPart(j);
//                }
            for (i = 0; i < messages.length; i++) {
                dtm.addRow(new Object[]{
                            new Boolean(false), //0-checkbox
                            InternetAddress.toString(NhanEmail.messages[i].getFrom()), //1-nguoigui
                            NhanEmail.messages[i].getSubject(), //2-tieude
                            //                            message.getReceivedDate().getYear() + 1900
                            //                            + "/" + message.gextReceivedDate().getMonth()
                            //                            + "/" + message.getReceivedDate().getDate(),
                            NhanEmail.messages[i].getSentDate(), //3-ngaygui
                            mp.getBodyPart(0).getContent().toString(), //4-noidung
                        //(messages[i].getFileName()).isEmpty() ? lbAttach : "", //4
                        //                            chkFile == true ? (JLabel) lbAttach : "", //5-cofilekhong
                        //                            chkFile == true ? mp.getBodyPart(1).getFileName() : ""}); //6-tenfile
                        //NhanEmail.messages[i].getFileName().isEmpty() ? new ImageIcon("//Other//icon//1371389699_attach.png", "") : ""
                        });
            }
        }

        ManHinhChinh.jTable1.setModel(dtm);
        ManHinhChinh.jTable1.setDefaultRenderer(Checkbox.class, new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
        ManHinhChinh.jTable1.changeSelection(0, 0, false, false);
    }
//    public static void dumpPart(Part p) throws IOException {
//        try {
//            String ct = p.getContentType();
//            filename1 = p.getFileName();
//            if (p.isMimeType("text/plain")) {
//                plain1 = (String) p.getContent();
//            } else if (p.isMimeType("multipart/*")) {
//                Multipart mp = (Multipart) p.getContent();
//                int count = mp.getCount();
//                for (int z = 0; z < count; z++) {
//                    dumpPart(mp.getBodyPart(z));
//                }
//            } else if (p.isMimeType(filename1)) //            InputStream is = m.getInputStream();
//            //            if (!(is instanceof BufferedInputStream)) {
//            //                is = new BufferedInputStream(is);
//            //            }
//            //            int c;
//            //            while ((c = is.read()) != -1) {
//            //                System.out.write(c);
//            //            }
//            //
//            //            String ct = m.getContentType();
//            //            String filename = m.getFileName();
//            //            if(m.isMimeType("text/plain")) {
//            //                if
//            //            }
//            //            
//            {
//                
//            }
//        } catch (MessagingException ex) {
//            Logger.getLogger(NhanEmail.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//    }
}
